<!-- Functions -->
<!-- Author: Edwin -->
<template>
  <div class='c-functions'>
    <el-container>
      <el-aside width="325px">
        <ul style="padding-left: 10px;">
          <li v-for="(functionItem, index) in functionList"
              :key="functionItem.id"
              role="menuitem"
              style="height: 50px; border: 1px solid #e4e7ed; padding-left: 10px; padding-right: 10px;">
            <div style="display:flex;align-items:center;justify-content:space-between;">
              <div>
                <el-link :underline="false"
                         @click="activeRule=index"
                         v-bind:class="{ active: index == activeRule }">
                  {{ functionItem.name }}
                </el-link>
              </div>
              <el-switch v-model="functionItem.enable">
              </el-switch>
            </div>
          </li>
        </ul>
      </el-aside>
      <el-main v-if="item">
        <el-tabs v-model="activeTab">
          <el-tab-pane :label="$t('custom.botStore.console.function.tabsTitle.setting')">
            <el-form label-width="120px">
              <el-form-item :label="$t('custom.botStore.console.function.formLabel.processName')">
                <el-input v-model="item.name"
                          :placeholder="$t('custom.botStore.console.function.formPlaceholder.processName')"></el-input>
              </el-form-item>
              <el-form-item :label="$t('custom.botStore.console.function.formLabel.scope')">
                <el-input v-model="item.scope"
                          readonly
                          :placeholder="$t('custom.botStore.console.function.formPlaceholder.scope')"></el-input>
              </el-form-item>
              <el-form-item :label="$t('custom.botStore.console.function.formLabel.triggerEvent')">
                <el-input v-model="item.triggerEvent"
                          readonly
                          :placeholder="$t('custom.botStore.console.function.formPlaceholder.triggerEvent')"></el-input>
              </el-form-item>
              <el-form-item :label="$t('custom.botStore.console.function.formLabel.version')">
                <el-input v-model="item.version"
                          readonly
                          :placeholder="$t('custom.botStore.console.function.formPlaceholder.version')"></el-input>
              </el-form-item>
              <el-form-item :label="$t('custom.botStore.console.function.formLabel.updatedDate')">
                <el-date-picker :value="timeformat(item.updateTime)"
                                style="width:100%;"
                                type="datetime"
                                readonly
                                :placeholder="$t('custom.botStore.console.function.formPlaceholder.updatedDate')"></el-date-picker>
              </el-form-item>
              <!-- -------------------------------- -->
              <el-form-item :label="$t('custom.botStore.console.function.formLabel.newFlag')">
                <el-date-picker v-model="item.newFlag"
                                style="width:100%;"
                                type="datetime"
                                :placeholder="$t('custom.botStore.console.function.formPlaceholder.newFlag')">
                </el-date-picker>
              </el-form-item>
              <!-- ----------------------------------- -->
              <el-form-item :label="$t('custom.botStore.console.function.formLabel.description')">
                <el-input v-model="item.description"
                          type="textarea"
                          :placeholder="$t('custom.botStore.console.function.formPlaceholder.description')"></el-input>
              </el-form-item>
              <el-form-item>
                <template v-if="sysBotName === 'Mspbots' || sysBotId === 5"></template>
                <template v-else>
                  <el-checkbox v-model="item.applyTenant">Apply To Client</el-checkbox>
                  <el-checkbox v-model="item.disable">Is Show Client</el-checkbox>
                </template>
              </el-form-item>
              <el-form-item v-for="(its, i) in parseParams"
                            :key="i"
                            :label="its.label">
                <template v-if="its.type === 'required'">
                  <el-input v-model="item.paramsValue[its.text]"
                            :placeholder="its.placeholder"></el-input>
                </template>
                <template v-if="its.type === 'text'">
                  <el-input v-model="item.paramsValue[its.text]"
                            :placeholder="its.placeholder"></el-input>
                </template>
                <template v-if="its.type === 'select'">
                  <div v-if="getSelectDataLists(its)"></div>
                  <el-select v-model="item.paramsValue[its.text]"
                             filterable
                             clearable
                             :placeholder="its.placeholder"
                             default-first-option>
                    <el-option v-for="(o,ii) in selectDataObj[`${its.text}ListsOrigin`]"
                               :key="ii"
                               :value="o[its.fieldValue]"
                               :label="o[its.fieldLabel]"></el-option>
                  </el-select>
                </template>

                <template v-if="its.type === 'customized-select'">
                  <div v-if="getSelectDataLists(its)"></div>
                  <el-select v-model="item.paramsValue[its.text]"
                             filterable
                             clearable
                             :placeholder="its.placeholder"
                             default-first-option>
                    <el-option v-for="its in its.selectList"
                               :key="its.value"
                               :label="its.label"
                               :value="its.value"></el-option>
                  </el-select>
                </template>
                <template v-if="its.type === 'autocomplete'">
                  <div v-if="getSelectDataLists(its)"></div>
                  <el-select v-model="item.paramsValue[its.text]"
                             filterable
                             clearable
                             multiple
                             collapse-tags
                             default-first-option>
                    <el-option v-for="(o,ii) in selectDataObj[`${its.text}ListsOrigin`]"
                               :key="ii"
                               :value="o[its.fieldValue]"
                               :label="o[its.fieldLabel]"></el-option>
                  </el-select>
                </template>
                <template v-if="its.type === 'customized-autocomplete'">
                  <div v-if="getSelectDataLists(its)"></div>
                  <el-select v-model="item.paramsValue[its.text]"
                             filterable
                             clearable
                             multiple
                             collapse-tags
                             default-first-option>
                    <el-option v-for="its in its.selectList"
                               :key="its.value"
                               :label="its.label"
                               :value="its.value"></el-option>
                  </el-select>
                </template>

                <template v-if="its.type === 'textarea'">
                  <quill-editor style="padding: 10px 0;"
                                ref="myTextEditor"
                                v-model="item.paramsValue[its.text]"
                                :hint="its.hint"
                                :placeholder="its.placeholder"
                                :label="its.label"
                                :options="editorOption"></quill-editor>
                </template>
                <template v-if="its.type === 'switch'">
                  <el-switch v-model="item.paramsValue[its.text]"></el-switch>
                </template>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          <el-tab-pane :label="$t('custom.botStore.console.function.tabsTitle.logic')">
            <codemirror :ref="`codemirror-logic`"
                        :options="cmOptions"
                        @changes="logicDataChange"></codemirror>
          </el-tab-pane>
          <el-tab-pane :label="$t('custom.botStore.console.function.tabsTitle.para')">
            <codemirror :ref="`codemirror-para`"
                        :options="cmOptions"
                        @changes="paraDataChange"></codemirror>
          </el-tab-pane>
        </el-tabs>
        <div class="c-functions-pane-footer">
          <el-button @click="saveBotRule"
                     :loading="loadingSaveBtn"
                     size="mini"
                     type="primary">{{ $t('custom.save') }}</el-button>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { debounce } from 'lodash'
import { codemirror } from 'vue-codemirror'
import 'codemirror/lib/codemirror.css'
import 'codemirror/theme/cobalt.css'
import 'codemirror/mode/groovy/groovy.js'
import { GlobalTimeformat } from '@/utils/common'

export default {
  props: {
    sysBotId: {
      type: [Number, String],
      default: null
    },
    sysBotName: {
      type: String,
      default: ''
    }
  },
  components: { codemirror },
  data () {
    return {
      editorOption: {
        name: '232',
        modules: {
          toolbar: [
            ['code-block'],
            [{ 'direction': 'rtl' }],
            ['bold', 'italic', 'underline', 'strike'],
            [{ 'color': [] }],
            [{ 'background': [] }],
            [{ 'header': 1 }, { 'header': 2 }],
            [{ 'script': 'sub' }, { 'script': 'super' }],
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'indent': '-1' }, { 'indent': '+1' }],
            [{ 'font': ['sans-serif', 'monospace', 'serif'] }],
            [{ 'size': ['small', false, 'large', 'huge'] }],
            [{ 'align': [] }],
            ['link'],
            ['clean']
          ]
        },
        theme: 'snow',
        placeholder: ''
      },
      cmOptions: {
        tabSize: 4,
        theme: 'cobalt',
        lineNumbers: true,
        line: true,
        mode: 'text/x-groovy',
        smartIndent: true,
        lineWrapping: true,
        foldGutter: true,
        matchBrackets: true,
        autoCloseBrackets: true,
        autoRefresh: true,
        autofocus: true
        // readOnly: 'nocursor'
      },
      functionList: [],
      activeRule: 0,
      activeTab: '0',
      loadingSaveBtn: false,
      selectDataObj: {},
      interfaceNoDataCount: 0
    }
  },
  computed: {
    computedActiveItem () {
      return this.functionList && this.functionList[this.activeRule]
        ? this.functionList[this.activeRule]
        : {}
    },
    parseParams () {
      const paramsJson = this.computedActiveItem.paramsJson
      if (paramsJson && JSON.parse(paramsJson)) {
        const fields = JSON.parse(paramsJson).fields || []
        return fields
      }
      return []
    },
    item () {
      return this.functionList[this.activeRule]
    }
  },
  watch: {
    'computedActiveItem.paramsJson': {
      handler: function (newValue, oldValue) {
        if (newValue && newValue !== oldValue) {
          this.computedParaView()
        }
      },
      deep: true
    },
    activeRule (val) {
      if (val) {
        this.setCodemirrorValue()
      }
    },
    activeTab (val) {
      if (val !== '0') {
        this.setCodemirrorValue()
      }
    }
  },
  created () {
    this.init()
  },
  methods: {
    saveBotRule () {
      this.loadingSaveBtn = true
      // this.functionList[this.activeRule].paramsValue = JSON.parse(this.functionList[this.activeRule].paramsValue)
      if (this.functionList[this.activeRule] && this.functionList[this.activeRule].paramsValue) {
        if (this.functionList[this.activeRule].enable === false) {
          this.functionList[this.activeRule].paramsValue.send = false
        }
        if (this.functionList[this.activeRule].paramsValue.send === false) {
          if (this.functionList[this.activeRule].paramsValue.sendEscalation) {
            this.functionList[this.activeRule].paramsValue.sendEscalation = false
          }
        }
      }
      this.$interface.botStore.updateBotRuleApi(this.functionList[this.activeRule], this.functionList[this.activeRule].id)
        .then(({ data: res }) => {
          this.loadingSaveBtn = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$message.success(res.msg)
        })
        .catch(() => { this.loadingSaveBtn = false })
    },
    init () {
      this.$interface.bots.getTenantScriptListApi({ botId: this.sysBotId, tenantId: this.$store.state.user.tenantCode })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.functionList = res.data
          this.$nextTick(() => {
            this.computedParaView()
          })
        }).catch(() => { })
    },
    logicDataChange: debounce(function (e) {
      try {
        this.functionList[this.activeRule].context = e.getValue()
      } catch (error) {
      }
    }, 800),
    paraDataChange: debounce(function (e) {
      try {
        this.functionList[this.activeRule].paramsJson = e.getValue()
      } catch (error) {
      }
    }, 800),
    setCodemirrorValue () {
      if (this.activeTab === '0') {
        return false
      }
      setTimeout(() => {
        try {
          const context = this.functionList[this.activeRule].context || ''
          const paramsJson = this.functionList[this.activeRule].paramsJson || ''
          this.activeTab === '1' && this.$refs[`codemirror-logic`].codemirror.setValue(context)
          this.activeTab === '2' && this.$refs[`codemirror-para`].codemirror.setValue(paramsJson)
        } catch (error) {
        }
      }, 100)
    },
    computedParaView () {
      const newValue = this.computedActiveItem.paramsJson
      if (newValue) {
        const fields = JSON.parse(newValue) && JSON.parse(newValue).fields ? JSON.parse(newValue).fields : []
        for (let i = 0; i < fields.length; i++) {
          try {
            if (
              !this.functionList[this.activeRule].paramsValue ||
              (this.functionList[this.activeRule].paramsValue && this.functionList[this.activeRule].paramsValue[fields[i].text] === undefined)
            ) {
              if (!this.functionList[this.activeRule].paramsValue) { this.functionList[this.activeRule].paramsValue = {} }
              this.$set(
                this.functionList[this.activeRule].paramsValue,
                fields[i].text,
                fields[i].defaultValue
              )
            }
          } catch (e) { }
        }
      }
    },
    getSelectDataLists (item) {
      if (this.interfaceNoDataCount > 10) {
        return false
      }
      if (item.interfaceUrl && this.hasSelectData(item)) {
        return false
      }
      const url = item.interfaceUrl
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      this.$interface.clientReport.getBoardListForBotApi(url, params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            this.selectDataObj[`${item.text}ListsOrigin`] = res.data
            this.selectDataObj = Object.assign({}, this.selectDataObj)
          }
          // Example:
          // {
          //   "fields": [
          //     {
          //        "text":"edwinTestSelect",
          //        "label":"Edwin Test",
          //        "type":"autocomplete",
          //        "defaultValue": null,
          //        "interfaceUrl": "/web/tasks/tennant_cw_board/findBoardList",
          //        "fieldLabel": "name",
          //        "fieldValue": "name"
          //     }
          //   ]
          // }
        }).catch(() => { })
    },
    hasSelectData (item) {
      try {
        if (this.selectDataObj[`${item.text}ListsOrigin`] && this.selectDataObj[`${item.text}ListsOrigin`].length > 0) {
          this.interfaceNoDataCount = 0
          return true
        } else {
          this.interfaceNoDataCount++
          return false
        }
      } catch (error) {
        this.interfaceNoDataCount++
        return false
      }
    },
    timeformat (time) {
      return GlobalTimeformat(time, 'HH:mm')
    }
  }
}
</script>

<style scoped lang="scss">
@import "./console.scss";

.el-link {
  margin-top: 10px;
}

.el-link.active {
  color: #17b3a3;
}
</style>
